<template>
  <el-dialog :title="title" :visible.sync="visible" width="600px" :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">

      <el-form-item label="文件：" prop="picUrl">
        <el-upload class="upload-demo" :action="fileAction" :headers="fileHeaders" :limit="1" :file-list="fileList"
          :before-upload="beforeFileUpload" :on-success="handleFileSuccess" :on-remove="handleRemove">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传图片，且不超过10MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="序号：" prop="sortNum">
        <el-input-number v-model="ruleForm.sortNum" :min="1" :max="50"></el-input-number>
      </el-form-item>
      <el-form-item label="图片说明：" prop="picDesc">
        <el-input v-model.trim="ruleForm.picDesc" type="textarea" show-word-limit placeholder="请输入" clearable
          class="input-w300" maxlength="50"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm('ruleForm')">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addCarousel, updateCarousel } from "@/api/home";
import { getToken } from "@/utils/auth";

export default {
  components: {},
  props: {
    visible: {
      default: false,
      type: Boolean
    },
    title: {
      default: '',
      type: String
    },
    editType: {
      default: 'add',
      type: String
    },
    editData: {
      default: {},
      type: Object
    }
  },
  data () {
    return {
      fileAction: process.env.VUE_APP_BASE_API + '/common/upload',
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],
      ruleForm: {
        picDesc: "",
        picUrl: "",
        picName: '',
        sortNum: 1,
        type: 2
      },
      rules: {
        picUrl: [
          { required: true, message: '请上传文件', trigger: 'blur' },
        ],
        sortNum: [
          { required: true, message: '请输入序号', trigger: 'change' },
        ],
      }
    };
  },
  watch: {
    visible (val) {
      if (val) {
        if (this.editType === 'edit') {
          this.ruleForm = JSON.parse(JSON.stringify(this.editData))
          if (this.ruleForm.picName && this.ruleForm.picUrl) {
            this.fileList = [
              { name: this.ruleForm.picName, url: this.ruleForm.picUrl }
            ]
          }
        }
      } else {
        this.ruleForm = {
          picDesc: "",
          picUrl: "",
          picName: '',
          sortNum: 1,
          type: 2
        }
        this.fileList = []
        this.resetForm('ruleForm')
      }
    }
  },
  methods: {
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    // 确定
    handleConfirm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await (this.ruleForm.id ? updateCarousel(this.ruleForm) : addCarousel(this.ruleForm))
          if (res.code === 200) {
            this.$message.success('保存成功');
            this.handleClose()
          }
        }
      });
    },
    // 文件上传前检查
    beforeFileUpload (file) {
      var FileExt = file.name.replace(/.+\./, "");
      const isLtM = file.size / 1024 / 1024 < 10;
      const fileTypeList = ['bmp', 'jpg', 'jpeg', 'png', 'gif']
      let isFileType = fileTypeList.indexOf(FileExt.toLowerCase()) > -1
      if (!isFileType || !isLtM) {
        this.$message.error('请检查文件格式以及大小');
      }
      return isFileType && isLtM;
    },
    // 文件上传成功
    handleFileSuccess (res, file) {
      if (res.code === 200) {
        this.ruleForm.picName = res.originalFilename || ''
        this.ruleForm.picUrl = res.fileName || ''
      }
    },
    // 文件删除
    handleRemove (file, fileList) {
      this.ruleForm.picUrl = ''
      this.ruleForm.picName = ''
    },
    // 取消
    handleCancel () {
      this.$emit('update:visible', false)
    },
    // 关闭
    handleClose () {
      this.$emit('update:visible', false)
      this.$emit('close')
    },

  }
};
</script>
<style lang='scss' scoped></style>
